using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia;
using Avalonia.Media;
using AvaloniaApplication1.Service;
using CommunityToolkit.Mvvm.Messaging;
using SukiUI;

namespace AvaloniaApplication1.ViewModels.CardViewModel;

public class TmphumViewModel:IRecipient<ThemeChangedMessage>,INotifyPropertyChanged
{
     private ThemeService _themeService;
    
    private IBrush _background = CreateLightGradient();

    public IBrush Background
    {
        get => _background;
        set => SetProperty(ref _background, value);
    }

    public TmphumViewModel(ThemeService themeService)
    {
      
        _themeService = themeService;
        //注册自己为消息接收者
        WeakReferenceMessenger.Default.Register<ThemeChangedMessage>(this);
       SukiTheme.GetInstance().OnBaseThemeChanged+= themeChanged =>
       {
           Background = themeChanged.Key.Equals("dark") ? CreateDarkGradient(): CreateLightGradient();
       };
       //监听
       _themeService.OnThemeChanged+= HandleThemeChanged;
       // ThemeService.Instance.OnThemeChanged += HandleThemeChanged;
    }

private void HandleThemeChanged(bool isDarkTheme)
    {
       Console.WriteLine($"theme changed to {isDarkTheme}");
    }

    public void Receive(ThemeChangedMessage message)
    {
       Console.WriteLine("accepted message");
    }
    private T SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return field;
        field = value;
        OnPropertyChanged(propertyName);
        return value;
    }
    public event PropertyChangedEventHandler? PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }


    // 创建深色渐变
    private static IBrush CreateDarkGradient() => new LinearGradientBrush
    {
        StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
        EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
        GradientStops = new GradientStops
        {
            new GradientStop { Color = Colors.HotPink, Offset = 0 },
            new GradientStop { Color = Color.FromRgb(204, 204, 255), Offset = 1 }
        }
    };
   // 创建亮色渐变
    private static IBrush CreateLightGradient() => new LinearGradientBrush
    {
        StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
        EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
        GradientStops = new GradientStops
        {
            new GradientStop { Color = Colors.Purple, Offset = 0 },
            new GradientStop { Color = Color.FromRgb(204, 204, 255), Offset = 1 }
        }
    };
}